package org.example.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.io.IOException;

// netty  支持很多协议，例如http  websocket  putobuf等

public class NResponse {

    private ChannelHandlerContext ctx;
    private HttpRequest req;

    public NResponse(ChannelHandlerContext ctx, HttpRequest req) {
        this.ctx = ctx;
        this.req = req;
    }

    public void write(String content) throws IOException {
        if (content == null || content.length() == 0) {
            return;
        }
        FullHttpResponse response = new DefaultFullHttpResponse(
                // 设置http版本为1.1
                HttpVersion.HTTP_1_1,
                // 设置响应状态码
                HttpResponseStatus.OK,
                // 设置输出值写出 编码为UTF-8
                Unpooled.wrappedBuffer(content.getBytes("UTF-8")));
        // 设置响应头
        response.headers().set("Content-Type", "text/html");
        ctx.writeAndFlush(response);

        ctx.close();
    }
}
